package com.kmproject.haifu.mvp.ui.activity;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.AppCompatImageView;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.StringUtils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.kmproject.haifu.R;

import butterknife.BindView;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 08/23/2019 18:04
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class WebViewActivity extends BaseActivity {
    @BindView(R.id.web_view)
    WebView web_view;
    @BindView(R.id.web_progress_bar)
    ProgressBar web_progress_bar;
    @BindView(R.id.img_message)
    AppCompatImageView img_message;

    private String mUrl;
    private String mTitle;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_web_view; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent != null) {
            mTitle = intent.getStringExtra("title");
            mUrl = intent.getStringExtra("url");
        }
        if (StringUtils.isTrimEmpty(mTitle)) {
            mTitle = getString(R.string.app_name);
        }
        if (StringUtils.isTrimEmpty(mUrl)) {
            throw new RuntimeException("Url cannot be empty.");
        }
        initView();
    }

    @SuppressLint("JavascriptInterface")
    private void initView() {
        setTitle(mTitle);
        WebSettings settings = web_view.getSettings();
        settings.setJavaScriptEnabled(true);//支持js
        settings.setUseWideViewPort(true);//将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        settings.setSupportZoom(true);//支持缩放，默认为true。是下面那个的前提。
        settings.setBuiltInZoomControls(false);//设置内置的缩放控件。若为false，则该WebView不可缩放
        settings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        settings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); //支持内容重新布局
        settings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        settings.setDatabaseEnabled(true);   //开启 database storage API 功能
        settings.setAppCacheEnabled(true);//开启 Application Caches 功能
        settings.setAppCacheMaxSize((5 * 1024 * 1024)); // 5MB
        settings.setGeolocationEnabled(true);//启用地理定位
//        //设置定位的数据库路径
//        val dir = context.applicationContext.getDir("database", Context.MODE_PRIVATE).path
//        settings.setGeolocationDatabasePath(dir)
        if (NetworkUtils.isConnected()) {
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
        }

        web_view.addJavascriptInterface(new JSInterfaceImpl(), "jsInterface");
        ValueAnimator progressAnimator = ValueAnimator.ofInt(0, 90);
        progressAnimator.setDuration(1000);
        progressAnimator.addUpdateListener(animation -> {
            int value = (int) animation.getAnimatedValue();
            web_progress_bar.setProgress(value * 10);
        });
        web_view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        web_view.setWebViewClient(new CustomWebViewClient(progressAnimator, this));
        web_view.loadUrl(mUrl);

        img_message.setVisibility(View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        web_view.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        web_view.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (web_view != null) {
            web_view.clearHistory();
//            (web_view.getParent()).removeView(web_view)
            web_view.loadUrl("about:blank");
            web_view.stopLoading();
            web_view.setWebChromeClient(null);
            web_view.setWebViewClient(null);
            web_view.destroy();
        }
    }

    static class CustomWebViewClient extends WebViewClient {
        private ValueAnimator valueAnimator;
        private WebViewActivity activity;

        public CustomWebViewClient(ValueAnimator valueAnimator, WebViewActivity activity) {
            this.valueAnimator = valueAnimator;
            this.activity = activity;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            activity.web_progress_bar.setVisibility(View.VISIBLE);
            valueAnimator.start();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            activity.web_progress_bar.setVisibility(View.GONE);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String phoneNumber = "";
            if (request != null && request.getUrl() != null) {
                String it = request.getUrl().toString();
                if (it.startsWith("tel:")) {
                    phoneNumber = it.replace("tel:", "").replace(" ", "").trim();
                    PhoneUtils.dial(phoneNumber);
                    return true;
                } else if (it.startsWith("mailto:")) {
                    phoneNumber = it.replace("mailto:", "");
                }
                if (RegexUtils.isEmail(phoneNumber)) {
                    PhoneUtils.sendSms(phoneNumber, "");
                    return true;
                } else if (it.startsWith("sms:")) {
                    phoneNumber = it.replace("sms:", "");
                    PhoneUtils.sendSms(phoneNumber, "");
                    return true;
                }
            }
            return super.shouldOverrideUrlLoading(view, request);
        }
    }

    interface JSInterface {
        // 实现一些js回调
    }

    class JSInterfaceImpl implements JSInterface {
    }
}
